package com.gongqi.gift.exception.handler;

import com.gongqi.gift.exception.BusinessException;
import com.gongqi.gift.exception.code.StatusCode;
import com.gongqi.gift.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice  //通知
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class) //处理业务异常
    public AjaxResult businessException(BusinessException e){
        e.printStackTrace();
       log.error(e.getMessage());
       return AjaxResult.me().setSuccess(false).setCode(e.getCode()).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)  //jsr303参数异常
    public AjaxResult businessException(MethodArgumentNotValidException e){
        StatusCode code = StatusCode.CODE_400;
        //获取所有字段验证错误
        StringBuilder builder = new StringBuilder();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            builder.append(fieldError.getDefaultMessage()+",");
        }
        String s = builder.toString();
        s = s.substring(0, s.length() - 1);
        log.error(s);
        return AjaxResult.me().setSuccess(false).setCode(code.getCode()).setMessage(s);
    }


    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        StatusCode code = StatusCode.CODE_500;
        e.printStackTrace();
        log.error(e.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(code.getCode()).setMessage(code.getMessage());
    }
}
